package net.qiqbframework.eventsourcing;

import net.qiqbframework.domains.event.infra.persistence.DomainEventPersistence;
import net.qiqbframework.eventhandling.EventMessage;
import net.qiqbframework.eventhandling.distributing.EventDistributor;
import net.qiqbframework.serialization.Serializer;

import java.util.List;

public class JdbcEventStorageEngine extends AbstractEventStorageEngine {

    private final DomainEventPersistence domainEventPersistence;

    protected JdbcEventStorageEngine(Builder builder) {
        super(builder);
        this.domainEventPersistence = builder.domainEventPersistence;
    }

    @Override
    protected void prepareCommit(List<? extends EventMessage<?>> events) {
        // 保存数据库
        domainEventPersistence.add(events, getEventSerializer());

    }

    public static JdbcEventStorageEngine.Builder builder() {
        return new JdbcEventStorageEngine.Builder();
    }


    public static class Builder extends AbstractEventStorageEngine.Builder {

        private DomainEventPersistence domainEventPersistence;

        public JdbcEventStorageEngine build() {
            return new JdbcEventStorageEngine(this);
        }

        public Builder domainEventPersistence(DomainEventPersistence domainEventPersistence) {
            this.domainEventPersistence = domainEventPersistence;
            return this;
        }

        @Override
        public JdbcEventStorageEngine.Builder eventDistributor(EventDistributor eventDistributor) {
            super.eventDistributor(eventDistributor);
            return this;
        }

        @Override
        public JdbcEventStorageEngine.Builder eventSerializer(Serializer eventSerializer) {
            super.eventSerializer(eventSerializer);
            return this;
        }
    }
}
